<?php
	/* favourites page recording script for the add_page.php page */

	//start the session
 	session_start();
 	
	//retrieves the file into an array where each line is a value
	$bookmark_number_file = '../bookmarks_data/bookmark_number_database.txt';
	$bookmark_num = file($bookmark_number_file);
	
 	//checks that the form has been submitted
 	if(isset($_POST['submit']) && $_POST['url'] != '' && $_POST['pageName'] != '')
	{
		$categories = htmlentities($_POST['category'], ENT_QUOTES); 			
		$www = "http://www.";
		$url = htmlentities($_POST['url'], ENT_QUOTES);
		$webAddress = $www . $url;
		$pageName = htmlentities($_POST['pageName'], ENT_QUOTES);
		$date_timestamp = time();
		$visitCounter = 0;
		$foundWebAddress = false;
		$foundPageName = false;
		$categoryInvalid = false;
		
		for($i = 0; $i < count($bookmark_num); $i++)
		{
			//goes through the file line by line
			$temp = explode(' | ', $bookmark_num[$i]);
		
			//creates an array of the favourites
			$favourite_num[$i] = array('category' => $temp[0], 'number' => $temp[1]);
		
			//this if statment looks to see if the categories match and if it does decreases the counter by one		
			if ($temp[0] == $categories)
			{
				$temp[1] += 1;
				$favourite_num[$i] = array('category' => $temp[0], 'number' => $temp[1]);
			}	
		}
		
		//sets what category was chosen from the dropdown list and add it to the $category variable	
		if($categories == 'Media')
		{
			$category = 'Media';
		}
		else if($categories == 'Games')
		{
			$category = 'Games';				
		}
		else if($categories == 'Social Networking')
		{
			$category = 'Social Networking';
		}
		else if($categories == 'Business')
		{
			$category = 'Business';
		}
		else if($categories == 'News')
		{
			$category = 'News';				
		}
		else if($categories == 'Please choose one:')
		{
			$categoryInvalid = true;
		}
		
		//if a category in the above if statement has not been selected $categoryInvalid is set to true 
		//leading to this error message being displaying	
		if($categoryInvalid)
		{
			$_SESSION['message'] = "<span style='color: red; font-weight: bold;'>A Category has not been selected.</span>";
			header('Location: ../add_page.php');
		}
		else
		{
			//defines the file location
			$bookmarks_file = '../bookmarks_data/bookmark_database.txt';
			//open's the file to allow us to read and write to it
			$file = fopen($bookmarks_file, 'a+');
		
			//if the file is empty, write to it, this also adds a plus 1 counter to the bookmark_number_database.txt file
			if(filesize($bookmarks_file) === 0)
			{
				fwrite($file, "$category | $webAddress | $pageName | $date_timestamp | $visitCounter");
				
				//close the file
				fclose($file);
				
				//opens the text file
				$fh = fopen($bookmark_number_file, "w");
				//sets a loop that will rewrite the favourites list
				foreach($favourite_num as $key => $value)
				{
					//cretes variables of the array values
					$category = trim($value['category']);
					$number = trim($value['number']);
		
					//validates the code so that no blank line is left st the end of the document writing
					if($key == 0)
					{
						//writes the variables to the text file
						fwrite($fh, "$category | $number");
					}
					else if($key > 0)
					{
						//writes the variables to the text file
						fwrite($fh, "\r\n$category | $number");
					}
				}
	
				//closes the text file
				fclose($fh);

				$_SESSION['message'] = "<span style='color:green; font-weight:bold;'>Page addition complete.</span>";
				header('Location: ../add_page.php');
			}
			else
			{
				/*
				Can't allow duplicate url's OR names so check's if the entered url or name has aleady 
				been taken.	
				rewind the pointer to the top of the file - this is because we 
				opened the file to append so the pointer is currently at the end of the file
				*/
					
				rewind($file);
					
				//now we loop through the file to see if there is a matching url or name in the file
				while(!feof($file))
				{
					//we go through the file line by line
					$line = fgets($file);
					$temp = explode(' | ', $line);
					
					//if a duplicate web address is found this sets $foundWebAddress to true,
					//breaking out of the while loop
					if($temp[1] == $webAddress)
					{
						$foundWebAddress = true;
						break;
					}
					
					//if a duplicate page name is found this sets $foundWebAddress to true;
					//breaking out of the while loop
					if($temp[2] == $pageName)
					{
						$foundPageName = true;
						break;
					}
				
				}
				//displays an error message if page name already exists
				if($foundPageName)
				{
					$_SESSION['message'] = "<span style='color: red; font-weight: bold;'>Page name already in use.</span>";
					header('Location: ../add_page.php');
				}
				else
				{
					//if web address is not found this writes to the file, 
					//adding a plus 1 counter to the bookmark_number_database.txt file
					if(!$foundWebAddress)
					{
						fwrite($file, "\r\n$category | $webAddress | $pageName | $date_timestamp | $visitCounter");
					
						//close the file
						fclose($file);
						
						//opens the text file
						$fh = fopen($bookmark_number_file, "w");
						//sets a loop that will rewrite the favourites list
						foreach($favourite_num as $key => $value)
						{
							//cretes variables of the array values
							$category = trim($value['category']);
							$number = trim($value['number']);
		
							//validates the code so that no blank line is left st the end of the document writing
							if($key == 0)
							{
								//writes the variables to the text file
								fwrite($fh, "$category | $number");
							}
							else if($key > 0)
							{
								//writes the variables to the text file
								fwrite($fh, "\r\n$category | $number");
							}
						}
						//displays a confirmation message if page is successfully added
						$_SESSION['message'] = "<span style='color:green; font-weight:bold;'>Page addition complete.</span>";
						header('Location: ../favourites_table.php');
					}
					else
					{
						//displays an error message if url already exists
						$_SESSION['message'] = "<span style='color: red; font-weight: bold;'>Page already exists.</span>";
						header('Location: ../add_page.php');
					}
				}
			}
		}	
	}
	else
	{
		//displays an error message if not all field have been filled in the form
		$_SESSION['message'] = "<span style='color: red; font-weight: bold;'>Not all field have been filled.</span>";
		header('Location: ../add_page.php');
	}
?>